<?php

namespace App\Admin\Forms;

use Dcat\Admin\Widgets\Form;
use App\Admin\Renderable\ActivityTable;
use App\Models\Activity;


class QRCodeForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {

        $scene = 'id=' . $input['activity_id'] . '&channel=' . $input['channel'];
        $url = 'pages/activity/index/index';
        $qrcode = app('App\Services\WechatService')->getUnlimitedQRCode($url, $scene);

        $data = [
            'qrcode' => $qrcode,
            'url' => $url . '?' . $scene
        ];
        return $this
            ->response()
            ->data($data);
        // ->refresh()
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->selectTable('activity_id', '活动')
            ->from(ActivityTable::make(['id' => $this->getKey()]))
            ->title('活动列表')
            ->dialogWidth('50%')
            ->model(Activity::class, 'id', 'title');
        $this->text('channel', '渠道')->required()->minLength(1)->maxLength(10)->help('只支持字母、数字，短破折号（-）和下划线（_）')->rules('required|alpha_dash|min:1|max:10');

        $this->html('<img id="qrcode" data-action="preview-img" src="https://dfac.obs.cn-north-4.myhuaweicloud.com/dfjk/images/17b9ec21d7cebbe1e0b107d6ea3fd6dc.jpg" style="max-width:200px;max-height:200px" class="img"><br/><br/><span id="qrcode_url">pages/index/index</span>', '小程序码');
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [];
    }

    protected function savedScript()
    {
        return <<<JS
        // data 为接口返回数据
        if (! data.status) {
            Dcat.error(data.message);
            return false;
        }

        $('#qrcode').attr('src',data.data.qrcode);
        $('#qrcode_url').html(data.data.url);
        Dcat.success('生成成功');
        // 中止后续逻辑（默认逻辑）
        return false;
JS;
    }
}
